#include <stdlib.h>
#include <stdio.h>
#include "output/output.h"

int eof_ = 0;

int my_callback(output_ctx* ctx, size_t available, void* user_data)
{
   //printf("Callback: %d bytes available\n", available);

   unsigned char buf[16*1024];
   size_t size = sizeof(buf);
   if (size > available)
   {
      size = available;
   }

   size_t r = read(0, buf, size);
   
   if (r > 0)
   {
      size = r;
      output_write_data(ctx, buf, &size);
      return 0;
   }
   else
   {
      eof_ = 1;
      output_stop(ctx);
      printf("EOF\n");
   }
   return -1;
}

int main()
{
   output_ctx* ctx = NULL;
   output_param param = { sizeof(output_param), 0 };
   param.rate = 22050;
   param.channels = 1;

   int err = 0;

   err = output_init(&ctx, "default");
   if (err != e_ok)
      return err;

   err = output_set_params(ctx, &param);
   if (err != e_ok)
      return err;

   err = output_set_callback(ctx, my_callback, NULL);
   if (err != e_ok)
      return err;

   err = output_start(ctx);
   if (err != e_ok)
      return err;

   int a = 0;
   while (a < 1000 && eof_ == 0)
   {
      //printf("Sleeping...\n");
      sleep(1);
      //printf("Sleep ended\n");
      if ((a % 100) == 0)
      {
         printf("sleep #%d\n", a);
      }
      //if (a == 100)
      {
         //break;
      }
      ++a;
   }

   err = output_stop(ctx);

   err = output_shutdown(ctx);
   return 0;
}
